<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox, ElUpload } from 'element-plus';
import { Plus } from "@element-plus/icons-vue";
import router from "@/router";

const userList = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

const defaultAvatar = "";

const token = localStorage.getItem('token');

const axiosInstance = axios.create({
  baseURL: 'http://localhost:8080/api/admin',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json'
  }
});

const fetchBookkeepingRecords = async (userAccount) => {
  await router.push({name: 'BookkeepingRecords', params: {account: userAccount}});
};

const searchQuery = ref('');

const pagedList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;

  let filteredList = userList.value;

  if (searchQuery.value) {
    const keyword = searchQuery.value.toLowerCase();
    filteredList = userList.value.filter(user =>
        user.account.toLowerCase().includes(keyword) ||
        user.username.toLowerCase().includes(keyword)
    );
  }

  return filteredList.slice(start, end);
});

const filteredTotal = computed(() => {
  if (searchQuery.value) {
    const keyword = searchQuery.value.toLowerCase();
    return userList.value.filter(user =>
        user.account.toLowerCase().includes(keyword) ||
        user.username.toLowerCase().includes(keyword)
    ).length;
  }
  return total.value;
});

const fetchUserList = async () => {
  loading.value = true;
  try {
    const response = await axiosInstance.get('/users');
    userList.value = response.data.data || [];
    total.value = userList.value.length;
  } catch (error) {
    console.error('Error fetching user list:', error);
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (event) => {
  pageSize.value = parseInt(event.target.value);
  currentPage.value = 1;
};

const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
  }
};

const nextPage = () => {
  if (currentPage.value < Math.ceil(total.value / pageSize.value)) {
    currentPage.value++;
  }
};

// 新增用户相关逻辑
const addUserForm = ref({
  account: '',
  username: '',
  password: '',
  avatar: null // 新增用户的头像状态
});

const addUserDialogVisible = ref(false);

const openAddUserDialog = () => {
  addUserDialogVisible.value = true;
};

const closeAddUserDialog = () => {
  addUserDialogVisible.value = false;
  addUserForm.value = {
    account: '',
    username: '',
    password: '',
    avatar: null
  };
};

// 处理新增用户的头像上传
const handleAddUserAvatarUpload = (file) => {
  if (!file) {
    ElMessage.error('请选择有效的文件');
    return false;
  }

  const isImage = file.type.startsWith('image/');

  if (!isImage) {
    ElMessage.error('请选择图片文件');
    return false;
  }

  const reader = new FileReader();
  reader.onload = (e) => {
    if (e.target && e.target.result) {
      addUserForm.value.avatar = e.target.result;
    }
  };
  reader.onerror = () => {
    ElMessage.error('文件读取失败');
  };
  reader.readAsDataURL(file);
  return false;
};

const handleAddUser = async () => {
  if (!addUserForm.value.account || !addUserForm.value.password) {
    ElMessage.error('账号和密码为必填项');
    return;
  }

  try {
    const response = await axiosInstance.post('/users', {
      account: addUserForm.value.account,
      username: addUserForm.value.username || addUserForm.value.account,
      password: addUserForm.value.password,
      avatar: addUserForm.value.avatar || defaultAvatar
    });

    if (response.data.success) {
      ElMessage.success('用户创建成功');
      closeAddUserDialog();
      await fetchUserList();
    } else {
      ElMessage.error(response.data.message || '用户创建失败');
    }
  } catch (error) {
    console.error('Error adding user:', error);
    ElMessage.error('用户创建失败，请检查输入信息');
  }
};

const editUserForm = ref({
  id: '',
  account: '',
  username: '',
  newPassword: '',
  avatar: null,
  bookCount: 0
});

const editUserDialogVisible = ref(false);
const currentEditingAccount = ref('');

const openEditUserDialog = (user) => {
  editUserForm.value = {
    id: user.id,
    account: user.account,
    username: user.username,
    avatar: user.avatar,
    bookCount: user.bookCount
  };
  currentEditingAccount.value = user.account;
  editUserDialogVisible.value = true;
};

const closeEditUserDialog = () => {
  editUserDialogVisible.value = false;
  editUserForm.value = {
    id: '',
    account: '',
    username: '',
    newPassword: '',
    avatar: null,
    bookCount: 0
  };
};

const handleEditUserAvatarUpload = (file) => {
  if (!file) {
    ElMessage.error('请选择有效的文件');
    return false;
  }

  const isImage = file.type.startsWith('image/');

  if (!isImage) {
    ElMessage.error('请选择图片文件');
    return false;
  }

  const reader = new FileReader();
  reader.onload = (e) => {
    if (e.target && e.target.result) {
      editUserForm.value.avatar = e.target.result;
    }
  };
  reader.onerror = () => {
    ElMessage.error('文件读取失败');
  };
  reader.readAsDataURL(file);
  return false;
};

const handleEditUser = async () => {
  try {
    const formData = {};
    if (editUserForm.value.username !== undefined) formData.username = editUserForm.value.username;
    if (editUserForm.value.account !== undefined) formData.newAccount = editUserForm.value.account;
    if (editUserForm.value.newPassword) formData.newPassword = editUserForm.value.newPassword;
    if (editUserForm.value.avatar !== undefined) formData.avatar = editUserForm.value.avatar;
    if (editUserForm.value.bookCount !== undefined) formData.bookCount = editUserForm.value.bookCount;

    if (!formData.avatar)  formData.avatar = defaultAvatar;

    const response = await axiosInstance.put(`/users/${currentEditingAccount.value}`, formData);

    if (response.data.success) {
      ElMessage.success('用户信息更新成功');
      closeEditUserDialog();
      await fetchUserList();
    } else {
      ElMessage.error(response.data.message || '用户信息更新失败');
    }
  } catch (error) {
    console.error('Error updating user:', error);
    ElMessage.error('用户信息更新失败，请检查输入信息');
  }
};

const handleDeleteUser = async (userAccount) => {
  ElMessageBox.confirm(
      '此操作将永久删除该用户，是否继续?',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      const response = await axiosInstance.delete(`/users/${userAccount}`);

      if (response.data.success) {
        ElMessage.success('用户删除成功');
        await fetchUserList();
      } else {
        ElMessage.error(response.data.message || '用户删除失败');
      }
    } catch (error) {
      console.error('Error deleting user:', error);
      ElMessage.error('用户删除失败，请检查后重试');
    }
  }).catch(() => {
    ElMessage.info('已取消删除操作');
  });
};

const clearAvatar = (formName) => {
  if (formName === 'addUserForm') {
    addUserForm.value.avatar = null;
  } else if (formName === 'editUserForm') {
    editUserForm.value.avatar = null;
  }
}

onMounted(() => {
  if (!token) {
    console.error('未找到认证令牌，请先登录');
    return;
  }
  fetchUserList();
});
</script>

<template>
  <div class="user-container">
    <h1>用户列表</h1>
    <div class="user-controls">
      <div class="search-container">
        <el-input
            v-model="searchQuery"
            placeholder="搜索账号或用户名"
            style="width: 300px;"
            clearable
        />
      </div>
      <div class="button-container">
        <el-button type="primary" @click="openAddUserDialog">新增用户</el-button>
      </div>
    </div>
    <div class="table-container">
      <table>
        <thead>
        <tr>
          <th>ID</th>
          <th>账号</th>
          <th>用户名</th>
          <th>头像</th>
          <th>创建时间</th>
          <th>更新时间</th>
          <th>记账次数</th>
          <th>选项</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="user in pagedList" :key="user.id">
          <td>{{ user.id }}</td>
          <td>{{ user.account }}</td>
          <td>{{ user.username }}</td>
          <td>
            <img v-if="user.avatar" :src="user.avatar" alt="用户头像" style="max-width: 50px; max-height: 50px;">
            <img v-else src="@/assets/default_avatar.png" alt="默认头像" style="max-width: 50px; max-height: 50px;">
          </td>
          <td>{{ user.addTime.replace('T', ' ') }}</td>
          <td>{{ user.updateTime.replace('T', ' ') }}</td>
          <td>{{ user.bookCount }}</td>
          <td>
            <el-button
                type="warning"
                size="small"
                @click="fetchBookkeepingRecords(user.account)"
            >
              查看账本记录
            </el-button>
            <el-button
                type="primary"
                size="small"
                @click="openEditUserDialog(user)"
            >
              编辑
            </el-button>
            <el-button
                type="danger"
                size="small"
                @click="handleDeleteUser(user.account)"
            >
              删除
            </el-button>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

    <div class="pagination">
      <div class="pagination-info">共 {{ filteredTotal }} 条</div>
      <div class="pagination-sizes">
        <select v-model="pageSize" @change="handleSizeChange">
          <option value="10">10</option>
          <option value="15">15</option>
          <option value="20">20</option>
        </select>
      </div>
      <div class="pagination-buttons">
        <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
        <span v-for="page in Math.ceil(filteredTotal / pageSize)" :key="page"
              @click="currentPage = page"
              :class="{ active: page === currentPage }">
      {{ page }}
    </span>
        <button @click="nextPage" :disabled="currentPage === Math.ceil(filteredTotal / pageSize)">下一页</button>
      </div>
    </div>
    <el-dialog
        v-model="editUserDialogVisible"
        title="编辑用户"
        width="500px"
    >
      <el-form :model="editUserForm" label-width="80px">
        <el-form-item label="ID">
          <el-input v-model="editUserForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="editUserForm.account" placeholder="请输入账号（最多11位）"></el-input>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" placeholder="请输入用户名（最多50位）"></el-input>
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="editUserForm.newPassword" type="password" placeholder="如不修改密码可留空"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="handleEditUserAvatarUpload"
          >
            <div v-if="editUserForm.avatar" class="avatar-wrapper">
              <img :src="editUserForm.avatar" class="avatar" alt="avatar">
              <span class="avatar-close" @click.stop="clearAvatar('editUserForm')">×</span>
            </div>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="记账次数">
          <el-input-number v-model="editUserForm.bookCount" :min="0"></el-input-number>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeEditUserDialog">取消</el-button>
          <el-button type="primary" @click="handleEditUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
        v-model="addUserDialogVisible"
        title="新增用户"
        width="500px"
    >
      <el-form :model="addUserForm" label-width="80px">
        <el-form-item label="账号">
          <el-input v-model="addUserForm.account" placeholder="请输入账号（最多11位）"></el-input>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="addUserForm.username" placeholder="请输入用户名（最多50位）"></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="addUserForm.password" type="password" placeholder="请输入密码（至少6位）"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :before-upload="handleAddUserAvatarUpload"
          >
            <div v-if="addUserForm.avatar" class="avatar-wrapper">
              <img :src="addUserForm.avatar" class="avatar" alt="avatar">
              <span class="avatar-close" @click.stop="clearAvatar('addUserForm')">×</span>
            </div>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeAddUserDialog">取消</el-button>
          <el-button type="primary" @click="handleAddUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.user-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
  display: flex;
  flex-direction: column;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
}

.table-container {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  margin-bottom: 20px;
  flex: 1;
  overflow: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  border: 1px solid #ebeef5;
  padding: 12px 10px;
  text-align: left;
}

th {
  background-color: #f5f7fa;
  color: #909399;
  font-weight: bold;
}

tr:nth-child(even) {
  background-color: #f9fafc;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin-top: 20px;
}

.pagination-info {
  margin-right: 10px;
}

.pagination-sizes select {
  padding: 5px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.pagination-buttons {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination-buttons button {
  padding: 6px 10px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
}

.pagination-buttons button:disabled {
  color: #c0c4cc;
  cursor: not-allowed;
}

.pagination-buttons span {
  display: inline-block;
  padding: 6px 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
}

.pagination-buttons span.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.user-controls {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-container {
  display: flex;
  align-items: center;
}

.button-container {
  display: flex;
  align-items: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 100px;
  height: 100px;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.avatar-wrapper {
  position: relative;
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
}

.avatar-close {
  position: absolute;
  top: -8px;
  right: -8px;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 50%;
  width: 24px;
  height: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  font-size: 16px;
  color: #909399;
  z-index: 1;
}

.avatar-close:hover {
  background-color: rgba(255, 255, 255, 0.9);
  color: #606266;
}
</style>